package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.CouponsSelectorRecycleAdapter;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.CouponsBean;
import com.weixin.paleituo.bean.CouponsTipsBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.RegisterProtocolPopupWindow;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 优惠券选择页面
 * 多选优惠券功能，
 * 列表数据由上个页面传入，
 * 如果有已选数据，也同步传入进行复选。
 * 选中之后返回选中数据集合，同时计算优惠金额返回。
 *
 * @author fengzhen
 * @version v1.0, 2018/4/2
 */
public class SelectorCouponsActivity extends BasePersonActivity {

    @BindView(R.id.recycle_coupons)
    RecyclerView mRecycleCoupons;

    private LoadingPagerHead mLoadingPagerHead;
    private CouponsSelectorRecycleAdapter mCouponsAdapter;
    private RegisterProtocolPopupWindow mCouponsUseTips;
    // 已经选中优惠券
    private ArrayList<CouponsBean> mChooseCoupons;

    private String proContent;
    private Dialog mLoadingDialog;
    private RegisterProtocolPopupWindow mInvoiceTipsPop;

    private List<CouponsBean> mCouponsList = new ArrayList<>();

    /**
     * 跳转选择优惠券界面
     *
     * @param coupons       所有优惠券列表信息  用于列表展示
     * @param chooseCoupons 已选择优惠券列表  用于复选
     */
    public static Intent call2SelectorCouponsActivity(Context context, ArrayList<CouponsBean> coupons, ArrayList<CouponsBean> chooseCoupons) {
        Intent intent = new Intent(context, SelectorCouponsActivity.class);
        intent.putExtra(Contans.INTENT_DATA, coupons);
        intent.putExtra(Contans.INTENT_EXTRA, chooseCoupons);
        return intent;
    }

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this) {
            @Override
            protected void close() {
                setResult(RESULT_CANCELED);
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(SelectorCouponsActivity.this, R.layout.activity_selector_coupons);
            }

            @Override
            protected void reLoading() {
            }
        };
        return mLoadingPagerHead;
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("优惠券");
        mTvSmalTitle.setText("使用说明");
        mTvSmalTitle.setVisibility(View.VISIBLE);

        Intent intent = getIntent();
        mCouponsList = (ArrayList<CouponsBean>) intent.getSerializableExtra(Contans.INTENT_DATA);
        mChooseCoupons = (ArrayList<CouponsBean>) intent.getSerializableExtra(Contans.INTENT_EXTRA);

        if (mCouponsList == null || mCouponsList.size() <= 0) {
            mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);
            return;
        }

        mRecycleCoupons.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mCouponsAdapter = new CouponsSelectorRecycleAdapter<CouponsBean>(this, mCouponsList);
        mRecycleCoupons.setAdapter(mCouponsAdapter);

        if (mChooseCoupons != null) {
            ArrayList<Integer> chooseIds = new ArrayList<>();
            for (CouponsBean couponsBean :
                    mCouponsList) {
                for (CouponsBean bean :
                        mChooseCoupons) {
                    if (bean.getId() == couponsBean.getId()) {
                        chooseIds.add(bean.getId());
                    }
                }
                mCouponsAdapter.setChooseCoupons(chooseIds);
            }
        }

        mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
    }

    @Override
    protected void save(final View v) {
        super.save(v);
        if (StringUtils.isEmpty(proContent)) {
            Observable observable = ApiUtils.getApi().getCouponsTips(Contans.defaultToken)
                    .compose(RxHelper.getObservaleTransformer())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            if (mLoadingDialog == null) {
                                mLoadingDialog = LoadingDialogUtils.createLoadingDialog(SelectorCouponsActivity.this, "");
                            }
                            mLoadingDialog.show();
                        }
                    }).subscribeOn(AndroidSchedulers.mainThread());
            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<CouponsTipsBean>(this) {

                @Override
                protected void _onNext(StatusCode<CouponsTipsBean> registerProBeanStatusCode) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    CouponsTipsBean dataProBean = registerProBeanStatusCode.getData();

                    proContent = dataProBean.getContent();
                    if (!StringUtils.isEmpty(proContent)) {
                        //弹出协议
                        if (mInvoiceTipsPop == null) {
                            mInvoiceTipsPop = new RegisterProtocolPopupWindow(SelectorCouponsActivity.this, proContent);
                        }
                        mInvoiceTipsPop.showAtLocation(v, Gravity.CENTER, 0, 0);
                    }
                }

                @Override
                protected void _onError(String message) {
                    ToastUtils.makeText(message);
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                }

            }, "", lifecycleSubject, false, true);

        } else {
            //弹出协议
            if (mInvoiceTipsPop == null) {
                mInvoiceTipsPop = new RegisterProtocolPopupWindow(this, proContent);
            }
            mInvoiceTipsPop.showAtLocation(v, Gravity.CENTER, 0, 0);
        }
    }

    @Override
    protected void returnMainActivity(View v) {
        super.returnMainActivity(v);
        setResult(RESULT_CANCELED);
    }

    @OnClick(R.id.btn_commit_activity_selector_coupons)
    public void onClickM() {
        if (mChooseCoupons != null) {
            mChooseCoupons.clear();
        } else {
            mChooseCoupons = new ArrayList<>();
        }
        Collection<Integer> allSelect = mCouponsAdapter.getAllSelect();
        BigDecimal decimal = new BigDecimal(0.0);
        for (int id :
                allSelect) {
            for (CouponsBean coupons :
                    mCouponsList) {
                if (id == coupons.getId()) {
                    mChooseCoupons.add(coupons);
                    decimal = decimal.add(new BigDecimal(coupons.getMoney()));
                }
            }
        }
        Intent intent = new Intent();
        intent.putExtra(Contans.INTENT_DATA, mChooseCoupons);
        intent.putExtra(Contans.INTENT_EXTRA, decimal.doubleValue());
        setResult(RESULT_OK, intent);
        finish();
    }
}
